// pages/search/search.js
import { SearchBook, getMyBooks, popSearches } from "../../utils/api.js";
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        path: 'https://img.yuncoding.cn/souti/book',
        search_Books: [],
        readHot: false,
        hidden: true
    },
    clearInput: function () {
        popSearches((res) => {
            this.setData({
                popSearches: res.data,
                readHot: false,
                inputVal: ""
            })
        })
    },
    addSearch: function (e) {
        var value = e.detail.value;
        if (!value) {
            popSearches((res) => {
                this.setData({
                    popSearches: res.data,
                    readHot: false,
                    inputVal: ''
                })
            })
        }
    },
    inputTyping: function (e) {
        var keyValue = e.detail.value;
        SearchBook(keyValue, (data) => {
            var joined = wx.getStorageSync("bookJoined") || [];
            data.forEach((item) => {
                if (joined.indexOf(item.id) != -1) {
                    item.joined = 1
                } else {
                    item.joined = 0;
                }
            });
            this.setData({
                search_Books: data,
                inputVal: keyValue,
                popSearches: null,
                readHot: true,
                hidden: false
            })

        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        new Promise((resolve, reject) => {
            if (app.globalData.token) {
                resolve()
            }
        }).then(() => {
            popSearches((res) => {
                this.setData({
                    popSearches: res.data
                })
            })
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.setData({
            inputVal: ""
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        getMyBooks((data) => {
            wx.showNavigationBarLoading()
            this.setData({
                myBooks: data
            });
            if (data.statusCode == 200) {
                wx.hideNavigationBarLoading();
                // 停止下拉动作
                wx.stopPullDownRefresh();
            }
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})